<template>
  <div class="homePage">
    <create-new :mode="mode" :show="createPageShow" @close="createPageShow=false" @refreshData="getDataAndShow"/>
    <filter-drawer :show="filterShow" :mode="mode" @getFilter="handleFilter" @close="filterShow=false"/>
    <el-container>
      <el-container>
        <el-aside>
          <div class="asideWrapper">
            <div class="aside">
              <div class="optionCard" @click="LetEmpShow" :class="{active:mode===0}">
                职工信息
              </div>
              <div class="optionCard" @click="LetDepShow" :class="{active:mode===1}">
                部门
              </div>
              <div class="optionCard" @click="LetTransShow" :class="{active:mode===2}">
                调动信息
              </div>
              <div class="emptyImage">
                <img :src="image" alt=""/>
              </div>
            </div>
          </div>
          <el-button
              :icon="Download"
              type="success"
              @click="backup"
          >备份</el-button>
        </el-aside>
        <el-main>
          <div class="leftWrapper">
            <div class="mainHeader">
              <div class="headerTitle">
                {{ header }}
              </div>
              <div class="operatorBox">
                <el-button round size="mini"
                           :icon="Filter"
                           @click="filterShow=true">
                  filter
                </el-button>
                <el-button
                    round size="mini"
                    type="danger"
                    @click="resetFilter">
                  reset
                </el-button>
                <el-button size="mini"
                           circle
                           :icon="Refresh"
                           type="success"
                           @click="getDataAndShow"/>
              </div>
            </div>
            <el-divider/>
            <div class="tableWrapper">
              <data-table
                  :mode="mode"
                  :data="info"
                  @showCreatePage="createPageShow=true"
                  @refreshData="getDataAndShow"/>
              <el-empty
                  description="select a table"
                  v-if="showEmpty"
                  :style="{marginTop:'110px'}"
              />
            </div>
            <el-pagination
                v-model:currentPage="currentPage"
                background
                layout="prev,pager,next"
                :total="pageNumber"/>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute, useRouter} from 'vue-router'
import {onMounted, ref, watch} from "vue";
import axios from "axios";
import {Filter, Refresh,Download} from "@element-plus/icons";
import {ElAside, ElButton, ElContainer, ElDivider, ElEmpty, ElMain, ElNotification, ElPagination} from "element-plus"

import image from '../../assets/1.png'
import DataTable from './table/dataTable.vue'
import FilterDrawer from "./filter/filterDrawer.vue"
import CreateNew from "./createNew/createNew.vue"

const map = ["在职", "兼职", "试用", "离职", "返聘", "退休"]
const ModMap = ["getEmpInfo", "getDepInfo", "getTransInfo"]

const route = useRoute()
const token = route.query.token
const router = useRouter()

const header = ref("select a table")
const mode = ref(0)
const showEmpty = ref(false)
const filterShow = ref(false)
const filterDisable = ref(true)
const pageNumber = ref(0)
const currentPage = ref(1)
const info = ref([])
const createPageShow=ref(false)

let data = []
let dataAfterFilter = []

const backup=()=>{
  axios.post(import.meta.env.VITE_APP_BASE_URL + "/api/backup?token="+token,null,{
    timeout:1000,
  }).then(res=>{
    if(res.status!==200){
      ElNotification({
        title: "error",
        message: "cannot get data"
      })
    }else{
      let blob=new Blob([res.data])
      let downloadEle=document.createElement('a');
      downloadEle.href=window.URL.createObjectURL(blob)
      downloadEle.download="backup.sql"
      downloadEle.click()
      downloadEle.remove()
    }
  })
}
watch(currentPage, (newp) => {
  info.value = dataAfterFilter.slice((newp - 1) * 20, newp * 20)
})

const resetFilter = () => {
  dataAfterFilter = data
  info.value = dataAfterFilter.slice((currentPage.value - 1) * 20, currentPage.value * 20)
}

function handleFilter(filter) {
  if (mode.value === 0) {
    dataAfterFilter = data.filter((item) => {
      if (filter == null) {
        return true
      }
      if (filter.id >= 0 && item.id !== filter.id) {
        return false
      }
      if (filter.name != null && item.name !== filter.name) {
        return false
      }
      if (filter.status != null && filter.status !== item.status) {
        return false
      }
      if (filter.arriveDate != null && filter.arriveDate.toISOString().slice(0, 10) !== item.arriveDate) {
        return false

      }
      if (filter.workPlace != null && filter.workPlace === item.position) {
        return false
      }
      if (filter.job != null && filter.job === item.job) {
        return false
      }
      return !(filter.depId !== -1 && filter.depId === item.departmentId);
    })

  } else if (mode.value === 1) {
    dataAfterFilter = data.filter((item) => {
      if (filter == null) {
        return true
      }
      if (filter.depId >= 0 && item.departmentId !== filter.depId) {
        return false
      }
      return !(filter.name != null && item.name !== filter.name);
    })
  } else {
    dataAfterFilter = data.filter((item) => {
      console.log(filter)
      console.log(item)
      if (filter == null) {
        return true
      }
      if (filter.id >= 0 && item.id !== filter.id) {
        return false
      }
      if (filter.workerId >= 0 && item.workId !== filter.workerId) {
        return false
      }
      if (filter.transDate != null && filter.transDate.toISOString().slice(0, 10) !== item.transDate) {
        return false
      }
      if (filter.inDepId >= 0 && filter.inDepId !== item.inDep) {
        return false

      }
      return !(filter.outDepId >= 0 && filter.outDepId === item.outDep);

    })
  }
  currentPage.value = 1
  info.value = dataAfterFilter.slice(0, 20)
  pageNumber.value = (Math.floor(dataAfterFilter.length / 20) + 1) * 10
}


async function LetEmpShow() {
  filterDisable.value = false
  showEmpty.value = false
  info.value = []
  mode.value = 0
  await getDataAndShow()
  header.value = "职工信息"
}

async function LetDepShow() {
  filterDisable.value = false
  showEmpty.value = false
  info.value = []
  mode.value = 1
  await getDataAndShow()
  header.value = "部门信息"
}

async function LetTransShow() {
  filterDisable.value = false
  showEmpty.value = false
  info.value = []
  mode.value = 2
  await getDataAndShow()
  header.value = "调动信息"
}

async function getDataAndShow() {
  let formData = new FormData()
  formData.append("token", token+'')
  let res = []
  try {
    res = await new Promise((resolve, reject) => {
      axios.post(import.meta.env.VITE_APP_BASE_URL + "/api/" + ModMap[mode.value], formData, {
        timeout: 1000,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(res => {
        if (res.status !== 200) {
          reject("some errors happen status:" + res.status)
        } else {
          resolve(res.data)
        }
      })
    })
  } catch (e) {
    ElNotification({
      title: "error",
      message: e
    })
    return
  }
  if (mode.value === 0) {
    res.forEach(item => {
      item.status = map[item.status - 1]

    })
  }
  if (res.length === 0) {
    showEmpty.value = true
  }
  data = res
  dataAfterFilter = res
  currentPage.value = 1
  pageNumber.value = (Math.floor(dataAfterFilter.length / 20) + 1) * 10
  info.value = res.slice(0, 20)

}

onMounted(() => {
  //checkToken
  if (!token) {
    router.push("/")
    return
  }
  let formData = new FormData()
  formData.append("token", token+'')
  axios.post(import.meta.env.VITE_APP_BASE_URL + "/api/checkToken", formData, {
    timeout: 1000,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }).then(res => {
    if (!res.data.res) {
      router.push("/")
    }else{
      getDataAndShow()
      header.value = "职工信息"
    }

  }).catch(err => {
    router.push("/")
    console.log(err)
  })
})

</script>

<style scoped>
.homePage {
  width: 90%;
  height: 95vh;
  background-color: white;
  border-radius: 10px;
  border: #89c8ee 1px solid;
  margin: 2vh auto auto;
  box-sizing: border-box;

}

.asideWrapper {
  height: 730px;
  width: 100%;
  /*background-color: #f3ebf3;*/
  box-sizing: border-box;
  padding: 30% 0 30% 0;

}

.aside {
  /*background: #e9f0f8;*/
  height: 100%;
  width: 270px;
  /*box-sizing: content-box;*/
  margin: 0 15px 0 15px;
  border-radius: 10px;
  padding: 15px 8px 15px 8px;
  box-sizing: border-box;
  box-shadow: 0 0 5px #c1dbe8;
}

.optionCard {
  width: 254px;
  height: 55px;
  background-color: #409EFF;
  color: white;
  border-radius: 5px;
  line-height: 55px;
  margin: 8px 0 8px 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  user-select: none;
}

.optionCard:hover {
  background-color: rgb(102, 177, 255);
}

.optionCard:active {
  background-color: rgb(58, 142, 230);
}

.leftWrapper {
  height: 800px;
  width: 100%;
  border-radius: 10px;
  border: #b5e5fd 1px solid;
}

.mainHeader {
  width: 100%;
  height: 36px;
  text-align: left;
  padding-left: 50px;
  box-sizing: border-box;
  font-size: 12px;

}

.tableWrapper {
  width: 1080px;
  margin: auto;
  height: 650px;
  overflow: scroll;
}

.emptyImage {
  width: 100%;
  height: 300px;
  opacity: 20%;
  border-radius: 20px;
  filter: grayscale(100%);
  box-sizing: border-box;
  padding-top: 65px;
  user-select: none;
}

.headerTitle {
  height: 16px;
  line-height: 16px;
  box-sizing: content-box;
  margin-top: 20px;
  float: left;
}

.operatorBox {
  float: right;
  margin-right: 50px;
  margin-top: 15px;
}

.active {
  background-color: #66ccff;
}
</style>